package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.Category;
import com.wms.bean.Coustomer;
import com.wms.config.Result;
import com.wms.service.CoustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("coustomer")
@CrossOrigin
public class CoustomerController {
    @Autowired
    CoustomerService coustomerService;

    @GetMapping("list")
    public Result getList() {
        List<Coustomer> list = coustomerService.list();
        return Result.success(list);
    }

    @PostMapping("add")
    public Result add(@RequestBody Coustomer coustomer){
        coustomerService.save(coustomer);
        Coustomer coustomerSerivceById = coustomerService.getById(coustomer.getCid());
        return Result.success("保存成功", coustomerSerivceById);
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") int id){
        boolean b= coustomerService.removeById(id);
        if(b){
            return Result.success("删除成功");
        }else{
            return Result.fail(201,"删除失败");
        }
    }

    @PutMapping("update")
    public  Result edit(@RequestBody Coustomer coustomer){
        boolean b = coustomerService.updateById(coustomer);
        Coustomer coustomer1 = coustomerService.getById(coustomer.getCid());
        if(b){
            return Result.success("修改成功", coustomer1);
        }else{
            return Result.fail(201,"修改失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<Coustomer> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result =coustomerService.page(page);
        } else {
            QueryWrapper<Coustomer> wrapper = new QueryWrapper<Coustomer>();
            wrapper.like("cid", searchtext)
                    .or().like("cname", searchtext);

            result =coustomerService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
}
